In [39]:
import re
print all([
not re.match("a","cat"),
re.search("a","cat"),
not re.search("c","dog"),
3 == len(re.split("[ab]","carbs")),
"R-D-" == re.sub("[0-9]","-","R2D2")
]) # prints true if all are true
In [40]:
class Set:
def __init__(self, values=None):
"""This is the constructor"""
self.dict={}
if values is not None:
for value in values:
self.add(value)
def __repr__(self):
"""Sting to represent object in class like a to_string function"""
return "set:"+str(self.dict.keys())
def add(self, value):
self.dict[value] = True
def contains(self, value):
return value in self.dict
def remove(self,value):
del self.dict[value]
In [41]:
#using the class
s = Set([1,2,3])
s.add(4)
s.remove(3)
print s.contains(3)
In [42]:
print s
In [43]:
def exp(base,power):
return base**power
#exp(2,power)
def two_to_the(power):
return exp(2,power)
print( two_to_the(3) )
In [19]:
def multiply(x,y): return x*y
products = map(multiply,[1,2],[4,5])
print products
In [ ]:
In [25]:
#example use
documents = ["a","b"]
def do_something(index,item):
print "index:"+str(index)+" Item:"+item
for i, document in enumerate(documents):
do_something(i,document)
In [29]:
def do_something(index ):
print "index:"+str(index)
for i, _ in enumerate(documents): do_something(i)
In [30]:
list1 = ['a','b','c']
list2 = [1,2,3]
zip(list1,list2)
Out[30]:
In [34]:
pairs = [('a', 1), ('b', 2), ('c', 3)]
letters, numbers = zip(*pairs) # * performs argument unpacking
print letters
print numbers
In [35]:
def doubler(f):
def g(x):
return 2 * f(x)
return g
def f1(x):
return x+1
g= doubler(f1)
print g(3)
In [38]:
def magic(*args, **kwargs):
print "unamed args", args
print "Key word args", kwargs
magic(1,2,key1="word1",key2="word2")
In [ ]: